<?php

namespace App\Http\Controllers\Mobile;

use App\Interfaces\CartService;
use App\Interfaces\RefundGoodsService;
use Illuminate\Http\Request;
use Gregwar\Captcha\CaptchaBuilder;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Interfaces\SmsService;
use App\Interfaces\UserService;
use Session,Auth,Validator,Input,Log;
use App\Models\User;
use App\Models\MessageCode;


class UserController extends Controller
{
    public function index(RefundGoodsService $refundGoodsService)
    {//dd("Dga");
        $user = Auth::user();
        $user_id =$user->user_id;
        $refundGoodsNumber = $refundGoodsService->countRefundGoodsNum($user_id);
        return view('mobile.user.index',compact('user_id','refundGoodsNumber','user'));
    }

    public function reg(){

        return view('mobile.user.register');
    }

    public function regOk(Request $request,SmsService $sms,UserService $userService){

        $phone = $request->get('mobile');
        $password = $request->get('password');

        $mesCode = $request->get('code');
        $agree = $request->get('agree');
        $is_phone = User::where('phone',trim($phone))->first();
        $email="";
        $message_id = Session::get('MsgCode_id');
        $validateRegCode = $sms->validateRegCode($message_id,$mesCode);

        //dd(Session::get('mcaptcha'));
        if($agree){
            if($validateRegCode){

                if($is_phone){
                    return response()->json(['status'=>0,'message'=>'该手机号已验证！']);
                }
                $register = $userService->reg($email,$password,$phone);

                if($register){
                    $mesCode = MessageCode::find(Session::get('MsgCode_id'));
                    $mesCode->delete();
                    $user = User::where('phone',trim($phone))->first();
                    Auth::login($user,true);
                    return response()->json(['status'=>1,'message'=>'注册成功！']);
                    //return view('mobile.user.regsuccess');
                }else{
                    return response()->json(['status'=>0,'message'=>'注册失败！']);

                }

            }else{
                return response()->json(['status'=>0,'message'=>'短信验证码错误！']);
            }

        }else{
            return response()->json(['status'=>0,'message'=>'是否同意服务条款！']);
        }

    }

    public function register(Request $request,SmsService $sms,UserService $userService){
        $chkCoke = $request->get('chkCoke');
        $phone = $request->get('phone');
        $mesCode = $request->get('mesCode');
        $password = $request->get('password');
        $agree = $request->get('checkbox');
        //dd($agree);

        $is_phone = User::where('phone',trim($phone))->first();
        $email="";

        $message_id = Session::get('MsgCode_id');
        $validateRegCode = $sms->validateRegCode($message_id,$mesCode);

//        if($chkCoke!=Session::get('mcaptcha')){
//            return response()->json(['status'=>0,'message'=>'验证码错误！']);
//        }
        if(!$validateRegCode){
            return response()->json(['status'=>0,'message'=>'短信验证码错误！']);
        }
        if($is_phone){
            return response()->json(['status'=>0,'message'=>'该手机号已验证！']);
        }
        if(!$agree){
            return response()->json(['status'=>0,'message'=>'是否同意服务条款']);
        }

        $register = $userService->reg($phone,$password,$phone);

        if($register){
            $mesCode = MessageCode::find(Session::get('MsgCode_id'));
            $mesCode->delete();
            $user = User::where('phone',trim($phone))->first();
            Auth::login($user);
            return response()->json(['status'=>1,'message'=>'注册成功！']);
            //return view('mobile.user.regsuccess');
        }else{
            return response()->json(['status'=>0,'message'=>'注册失败！']);
        }

    }

    public function regsuccess(Request $request){
        $user = Auth::user();
        return view('mobile.user.regsuccess',compact('user'));
    }

    public function setting(){
        return view('mobile.user.setting');
    }

    public function resetPassword(){
        $user = Auth::user();
        return view('mobile.user.resetpassword',compact('user'));
    }
    public function resetOk(Request $request,UserService $userService){
        $user = User::find(Auth::user()->id);
        //dd($user);
        $pwd = $request->get('pwd');
        $newPwd = $request->get('newPwd');
        $rePwd = $request->get('rePwd');


        if(md5($pwd) != $user->password){
            return response()->json(['status'=>0,'message'=>'原密码输入有误']);
//            return redirect()->back()->with('请输入正确的密码');
        }
        if($pwd === $newPwd){
            return response()->json(['status'=>0,'message'=>'旧密码和新密码一样']);
//            return redirect()->back()->with('旧密码和新密码一样');
        }
        if($newPwd != $rePwd){
            return response()->json(['status'=>0,'message'=>'两次输入的密码不一样']);
//            return redirect()->back()->with('两次输入的密码不一样');
        }
        //dd($newPwd);
        $user = $userService->updatePaw($user->user_name,$pwd,$newPwd);
        if($user){
            return response()->json(['status'=>1,'message'=>'密码修改成功！3秒后重新登录']);
//            return redirect('/user/login');
        }

    }

    public function logout(Request $request){
        $returnUrl = $request->get('returnUrl');

        if(Auth::check()){

            Auth::logout();
            return response()->json(['status'=>1,'message'=>'退出成功']);
        }

    }

    public function login(Request $request){
        $returnUrl = $request->get('return_url');
        return view('mobile.user.login',compact('returnUrl'));
    }

    public function loginOk(Request $request,CartService $cartService){
        $returnUrl = $request->get('return_url');
//dd($returnUrl);
        if(User::where('email',trim(Input::get('user_name')))->first()){
            $user = User::where('email',trim($request->get('user_name')))->first();
        }elseif(User::where('phone',trim($request->get('user_name')))->first()){
            $user = User::where('phone',trim($request->get('user_name')))->first();
        }elseif(User::where('user_name',trim($request->get('user_name')))->first()){
            $user = User::where('user_name',trim($request->get('user_name')))->first();
        }else{
            return response()->json(['status'=>0,'message'=>'用户不存在！','returnUrl'=>$returnUrl]);
            //return redirect()->back()->withInput()->withErrors('用户不存在');
        }
        $password = $request->get('password');
        if($user->is_disabled==1){
            return response()->json(['status'=>0,'message'=>'用户被禁止登录！','returnUrl'=>$returnUrl]);
        }
        if($password==''||md5($password)!=$user->password){
            return response()->json(['status'=>0,'message'=>'用户名或密码错误！','returnUrl'=>$returnUrl]);
        }
        Auth::login($user,true);
        if(Auth::check()){
            //dd('dfa');
            $user->last_login_ip = $request->ip();
            $user->last_login_time = date('Y-m-d H:i:s',time());
            $user->save();

        }
        //dd('dfadf');
        //关联购物车商品
        $cartService->linkSessionToUser($request->get('session_id'),$user->id);

        if ($returnUrl){
            return response()->json(['status'=>1,'message'=>'登录成功！','returnUrl'=>$returnUrl]);
        }else{
            return response()->json(['status'=>1,'message'=>'登录成功！','returnUrl'=>'/']);
        }

    }




    public function sms(SmsService $sms,Request $request){
        //dd("dga");
        $chkCode = $request->get('chkCode');
        //dd(Session::get('chkCode'));
        $sendLiveTime=60;
        $phone = $request->phone;
        $is_phone = User::where('phone',trim($phone))->first();
        if($chkCode==Session::get('chkCode')){
            if($is_phone){

                return response()->json(['status'=>0,'message'=>'该手机号已注册！']);
            }

            $sendTime = MessageCode::where('phone',$phone)->orderBy('send_time','desc')->pluck('send_time');
            if($sendTime){
                if(strtotime(date('Y-m-d H:i:s',time()))-strtotime($sendTime)>=$sendLiveTime){

                    $message_id =  $sms->sendRegMsg($phone);
                }
            }else{
                $message_id =  $sms->sendRegMsg($phone);
            }
            if($message_id){
                Session::put('MsgCode_id',$message_id);
                Session::save();
                return response()->json(['status'=>1,'message'=>'发送成功！']);
            }else{
                return response()->json(['status'=>0,'message'=>'发送失败！']);
            }

        }else{
            return response()->json(['status'=>0,'message'=>'验证码错误！']);
        }

    }


    public function captcha($tmp,CaptchaBuilder $builder)
    {
//dd("dfa");
        //图片效果设置样放在 build 方法前面
        $builder->setMaxBehindLines(2);                 //背景干扰线
        $builder->setMaxFrontLines(0);                  //前置干扰线
        $builder->setMaxOffset(6);                      //设置偏移值
        $builder->setDistortion(false);                //是否失真

        //可以设置图片宽高及字体
        $builder->build($width = 100, $height = 38, $font = null);

        //获取验证码的内容
        $phrase = $builder->getPhrase();
//dd($phrase);
        //把内容存入session
        Session::put('chkCode', $phrase);

        //Session::flash('milkcaptcha', $phrase);
        //生成图片
        header("Cache-Control: no-cache, must-revalidate");
        header('Content-Type: image/jpeg');
        $builder->output();
        $builder->inline();
    }

    public function findPassword(Request $request){
        $step = Session::get('step');
        if($step){
            Session::put('step','');
            Session::save();
            return view('mobile.user.findpassword'.$step);
        }else{
            return view('mobile.user.findpassword1');
        }

    }


    public function checkStep(Request $request,User $user,SmsService $sms){

        if($request->get('step')==1){
            if(User::where('email',trim(Input::get('user_name')))->first()){
                $user = User::where('email',trim($request->get('user_name')))->first();
            }elseif(User::where('phone',trim($request->get('user_name')))->first()){
                $user = User::where('phone',trim($request->get('user_name')))->first();
            }elseif(User::where('user_name',trim($request->get('user_name')))->first()){
                $user = User::where('user_name',trim($request->get('user_name')))->first();
            }else{
                return response()->json(['status'=>0,'message'=>'用户不存在！','returnUrl'=>'/user/find_password','step'=>'1']);
            }
            Session::put('phone',$user->phone);
            Session::put('step',2);
            Session::save();
            //dd($user);
            return response()->json(['status'=>1,'returnUrl'=>'/user/find_password','step'=>'2']);

        }
        if($request->get('step')==2){
            $phone = $request->get('phone');
            $msgcod = $request->get('msgcode');
            $message_id = Session::get('message_id');
            $validateRegCode = $sms->validateRegCode($message_id,$msgcod);
            if($validateRegCode){
                $messageCode = MessageCode::find($message_id);
                $messageCode->delete();
                Session::put('step',3);
                Session::save();
                return response()->json(['status'=>1,'phone'=>$phone,'returnUrl'=>'/user/find_password','step'=>'3']);
            }else{
                Session::put('step',2);
                Session::save();
                return response()->json(['status'=>0,'message'=>'短信验证码错误,请重新获取','returnUrl'=>'/user/find_password','step'=>'2']);
            }
        }
        if($request->get('step')==3){
            $phone = Session::get('phone');
            $newPassword = $request->get('newPassword');
            $user = User::where('phone',$phone)->first();
            $user->password=$newPassword;
            $user->save();
            Session::put('step',4);
            Session::save();
            return response()->json(['status'=>1,'phone'=>$phone,'returnUrl'=>'/user/find_password','step'=>'4']);
        }else{
            Session::put('step',1);
            Session::save();
            return response()->json(['status'=>1,'returnUrl'=>'/user/find_password','step'=>'4']);
        }

    }

    public function sendSms(Request $request,SmsService $sms){
        $sendLiveTime=60;
        $phone = $request->phone;
        //dd($phone);
        $sendTime = MessageCode::where('phone',$phone)->orderBy('send_time','desc')->pluck('send_time');

        if($sendTime){
            if(strtotime(date('Y-m-d H:i:s',time()))-strtotime($sendTime)>=$sendLiveTime){
                $message_id =  $sms->sendRegMsg($phone);
            }else{
                return response()->json(['status'=>0,'message'=>'该手机已发送验证码！']);
            }
        }else{
            $message_id =  $sms->sendRegMsg($phone);
            //dd($message_id);
        }

        if($message_id){
            Session::put('message_id',$message_id);
            Session::save();
            return response()->json(['status'=>1,'message'=>'发送成功！']);
        }else{
            return response()->json(['status'=>0,'message'=>'发送失败！']);
        }

    }

}
